//
//  AccountWithdrawTableViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/11.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "AccountDepositNextViewController.h"
#import "ChooseView.h"
#import "AccountDepositRequestViewController.h"
#import "ChangeVerifyView.h"
#import "SelectCountryTableViewController.h"
#import "BankAccountListEntity.h"
#import "SheetView.h"
#import "DepositMethodEntity.h"
#import "AddBankAccountTableViewController.h"
#import "BankListTableViewController.h"


@interface AccountDepositNextViewController ()

@property (weak, nonatomic) IBOutlet UILabel *message;
@property (weak, nonatomic) IBOutlet UIButton *ConfirmButton;
@property (weak, nonatomic) IBOutlet UILabel *countryTitle;
@property (weak, nonatomic) IBOutlet UITextField *countryTextField;

@property (weak, nonatomic) IBOutlet UILabel *methodTitle;
@property (weak, nonatomic) IBOutlet UIView *methodBgView;
@property (weak, nonatomic) IBOutlet UILabel *amountTitle;
@property (weak, nonatomic) IBOutlet UILabel *available;
@property (weak, nonatomic) IBOutlet UILabel *availableValue;

@property (strong, nonatomic) NSArray<DepositMethodEntity *> *chooseMethodArray;
@property (strong, nonatomic) ChooseView *chooseView;
@property (nonatomic, strong) NSMutableArray *chooseTitleArray;
@property (nonatomic, assign) BOOL isBank;
// 选择城市
@property (strong, nonatomic) CountryEntity *country;


@property (weak, nonatomic) IBOutlet UITextField *bankName;
@property (weak, nonatomic) IBOutlet UITextField *bankHoldName;
@property (weak, nonatomic) IBOutlet UITextField *accountNumber;

@property (nonatomic, strong) NSArray *allBankList;
@property (nonatomic, strong) BankAccountListEntity *selectBankAccount;

@property (weak, nonatomic) IBOutlet UITextField *amountTextField;

// 提取或存入货币的id
@property (nonatomic, strong) NSString *currencyId;

@property (nonatomic, strong) NSArray *bank_account_required_fields;

@end

@implementation AccountDepositNextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = [NSString stringWithFormat:@"%@ %@", @[JFMainLocalizedString(@"deposit.deposit"), JFMainLocalizedString(@"exchange.exchange"), JFMainLocalizedString(@"withdraw.transfer"), JFMainLocalizedString(@"withdraw.withdraw")][self.type], self.balanceEntity.asset_symbol];
    self.amountTextField.placeholder = JFMainLocalizedString(@"deposit.please-enter-amount");
    self.countryTitle.text = JFMainLocalizedString(@"deposit.country");
    self.countryTextField.placeholder = JFMainLocalizedString(@"deposit.please-select-country");
    self.bankName.placeholder = JFMainLocalizedString(@"withdraw.registered-account");
    [self.ConfirmButton setTitle:JFMainLocalizedString(@"confirm") forState:UIControlStateNormal];
    self.available.text = JFMainLocalizedString(@"withdraw.available");
    self.amountTitle.text = JFMainLocalizedString(@"deal.amount");
    if (self.type == 0) { // Deposit
//        self.amountTitle.text = [NSString stringWithFormat:@"%@ %@", JFMainLocalizedString(@"deposit.deposit"), JFMainLocalizedString(@"deal.amount")];
        self.message.text = JFMainLocalizedString(@"deposit.message");
        self.methodTitle.text = JFMainLocalizedString(@"deposit.method");
    }else if (self.type == 3){
//        self.amountTitle.text = [NSString stringWithFormat:@"%@ %@", JFMainLocalizedString(@"withdraw.withdraw"), JFMainLocalizedString(@"deal.amount")];
        self.message.text = JFMainLocalizedString(@"withdraw.fiat-message");
        self.methodTitle.text = JFMainLocalizedString(@"withdraw.method");
    }
    
    
    
    [self.ConfirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0xCCCCCC) size:self.ConfirmButton.frame.size] forState:UIControlStateDisabled];
    [self.ConfirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0x70896A) size:self.ConfirmButton.frame.size] forState:UIControlStateNormal];
    self.ConfirmButton.enabled = NO;
    
    self.availableValue.text = self.balanceEntity.available_balance_display;
    
    Currencie *currencie = [Currencies() getCurrencieWithDisplaySymbol:self.balanceEntity.asset_symbol];
    self.currencyId = currencie.ID;
    NSString *default_country = currencie.default_country;
    if (default_country.length) {
        self.country = [Currencies() getCountryEntityWithCountryId:default_country];
    }
    
    [self requestBankList];
}

- (void)requestFiatMethod {
    WEAKSELF
    if (self.type == 0) {
        [HYNetHelper depositMethods:self.currencyId callback:^(JFResultVo *resultVo) {
            if (!resultVo.errorNo) {
                weakSelf.chooseMethodArray = [NSArray yy_modelArrayWithClass:[DepositMethodEntity class] json:resultVo.results[@"data"]];
                [weakSelf updateChooseView];
            }
        }];
    }else {
        [HYNetHelper withdrawFiatMethodWithCurrencyId:self.currencyId country:self.country.countryId callBack:^(JFResultVo *resultVo) {
            if (!resultVo.errorNo) {
                weakSelf.chooseMethodArray = [NSArray yy_modelArrayWithClass:[DepositMethodEntity class] json:resultVo.results[@"data"]];
                
                [weakSelf updateChooseView];
            }
        }];
    }
}

- (void)reqestBankRequirement {
    WEAKSELF
    [HYNetHelper bankAccountRequirements:self.country.countryId callback:^(JFResultVo *resultVo) {
        if (!resultVo.errorNo) {
            weakSelf.bank_account_required_fields = resultVo.results[@"bank_account_required_fields"];
        }
    }];
}

- (void)requestBankList {
    WEAKSELF
    [HYNetHelper bankAccount:^(JFResultVo *resultVo) {
        if (resultVo.errorNo == 0) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[BankAccountListEntity class] json:resultVo.results[@"data"]];
            NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:5];
            for (BankAccountListEntity *bank in array) {
                if (!bank.disabled) {
                    [array1 addObject:bank];
                }
            }
            weakSelf.allBankList = [NSArray arrayWithArray:array1];
        }
    }];
}

- (void)setCountry:(CountryEntity *)country {
    if (_country != country) {
        _country = country;
        
        [self requestFiatMethod];
        
        self.countryTextField.text = country.countryName;
        
        self.selectBankAccount = nil;
    }
}

- (void)setSelectBankAccount:(BankAccountListEntity *)selectBankAccount {
    if (_selectBankAccount != selectBankAccount) {
        _selectBankAccount = selectBankAccount;
        
        self.bankName.text = selectBankAccount.datas.bank_name;
        self.accountNumber.text = selectBankAccount.datas.account_number;
        self.bankHoldName.text = selectBankAccount.datas.account_name;
        
        [self.tableView reloadData];
    }
}

- (void)updateChooseView {
    if (self.chooseView.superview) {
        [self.chooseView removeFromSuperview];
    }
    
    self.chooseTitleArray = [NSMutableArray arrayWithCapacity:2];
    for (DepositMethodEntity *entity in self.chooseMethodArray) {
        [self.chooseTitleArray addObject:entity.name.name];
    }
    
    
    WEAKSELF
    self.chooseView = [[ChooseView alloc]initWithFrame:CGRectMake(15, 55, SCREEN_WIDTH - 30, 15) itemArray:self.chooseTitleArray];
    self.chooseView.vauleChange = ^(NSInteger selectIndex) {
        [weakSelf updateIsBank];
    };
    [self.methodBgView addSubview:self.chooseView];
    
    [self updateIsBank];
}

- (void)updateIsBank {
    DepositMethodEntity *method = self.chooseMethodArray[self.chooseView.selectIndex];
    self.isBank = [method.name.en_US isEqualToString:@"Bank Transfer"];
    if ([method.name.en_US isEqualToString:@"Pick up"]) {
        self.available.hidden = self.availableValue.hidden = NO;
    }
    [self.tableView reloadData];
}

- (void)pushAddBankVC {
    AddBankAccountTableViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"AddBankAccountTableViewController"];;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Table view data source

- (IBAction)selectCountryAction:(id)sender {
    SelectCountryTableViewController *vc = [[SelectCountryTableViewController alloc]init];
    WEAKSELF
    vc.selectAction = ^(CountryEntity * _Nonnull country) {
        weakSelf.country = country;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)selectAccount:(id)sender {
    WEAKSELF
    BankListTableViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"BankListTableViewController"];
    vc.type = 1;
    vc.bankCountry = self.country.countryId;
    vc.selectBank = ^(BankAccountListEntity * _Nonnull data) {
        weakSelf.selectBankAccount = data;
    };
    [self.navigationController pushViewController:vc animated:YES];
    
//    if (self.currentCountBankList.count == 0) {
//        FZAlertController *vc = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"Captcha_ico_b"] title:nil customView:nil message:@"Please add bank account to continue"];
//        vc.showCloseBtn = YES;
//        FZAlertAction *action = [FZAlertAction actionWithTitle:@"Add bank account" style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
//            [weakSelf pushAddBankVC];
//                            }];
//        [vc addAction:action];
//        [self presentViewController:vc animated:YES completion:nil];
//    }else {
//        NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.currentCountBankList.count];
//        for (BankAccountListEntity *bank in self.currentCountBankList) {
//            [array addObject:bank.datas.bank_name];
//        }
//
//        SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
//        view.frame = self.navigationController.view.bounds;
//        view.titleArray = array;
//        view.selectAction = ^(NSInteger index) {
//            weakSelf.selectBankAccount = weakSelf.currentCountBankList[index];
//        };
//        [self.navigationController.view addSubview:view];
//    }
}


- (IBAction)editChangeAction:(id)sender {
    if ((self.countryTextField.text.length > 0) && (self.amountTextField.text.length > 0)) {
        self.ConfirmButton.enabled = YES;
    }else {
        self.ConfirmButton.enabled = NO;
    }
}

- (IBAction)confirmAction:(id)sender {
//    if (self.type == 0) { // Deposit
        DepositMethodEntity *method = self.chooseMethodArray[self.chooseView.selectIndex];
        
        DepositRequestEntity *entity = [[DepositRequestEntity alloc]init];
        entity.amount = self.amountTextField.text;
        entity.country = self.countryTextField.text;
        entity.countryId = self.country.countryId;
        entity.method = self.chooseTitleArray[self.chooseView.selectIndex];
        entity.method_id = method.ID;
        entity.wallet_id = self.wallet_id;
        entity.asset_symbol = self.balanceEntity.asset_symbol;
        entity.bankAccount = self.selectBankAccount;
        entity.currency_id = self.currencyId;
    
    if (self.type == 3) {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
        for (RequirementsEntity *requirement in method.requirements) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
            [dic setObj:requirement.ID forKey:@"fiat_withdraw_method_settlement_details_requirements_id"];
            NSString *type = requirement.field_name.en_US;
            if ([type isEqualToString:@"Account Number"]) {
                [dic setObj:self.selectBankAccount.datas.account_number forKey:@"value"];
            }else if ([type isEqualToString:@"Account Holder Name"]) {
                [dic setObj:self.selectBankAccount.datas.account_name forKey:@"value"];
            }else if ([type isEqualToString:@"Bank Name"]) {
                [dic setObj:self.selectBankAccount.datas.bank_name forKey:@"value"];
            }else if ([type isEqualToString:@"Bank Detail"]) {
                [dic setObj:self.selectBankAccount.datas.bank_detail forKey:@"value"];
            }else if ([type isEqualToString:@"Country"]) {
                [dic setObj:self.selectBankAccount.datas.country forKey:@"value"];
            }
            [array addObject:dic];
        }
        entity.withdrawBankData = [NSArray arrayWithArray:array];
    }
    
        AccountDepositRequestViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"AccountDepositRequestViewController"];
        vc.entity = entity;
        vc.type = self.type;
        [self.navigationController pushViewController:vc animated:YES];
//    }else if (self.type == 3){
//        ChangeVerifyView *view = [[[NSBundle mainBundle] loadNibNamed:@"ChangeVerifyView" owner:nil options:nil] firstObject];
//        view.frame = CGRectMake(0, 0, CUSTOMVIEW_WIDTH, 110);
//        FZAlertController *vc = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"Captcha_ico_b"] title:nil customView:view message:nil];
//        vc.showCloseBtn = YES;
//        FZAlertAction *action = [FZAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
//                            }];
//        [vc addAction:action];
//        [self presentViewController:vc animated:YES completion:nil];
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        {
            CGRect rect = [self.message.text boundingRectWithSize:CGSizeMake(AWSCREEN_WIDTH - 32, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.message.font} context:nil];
            return rect.size.height + 20;
        }
            break;
        case 3:
            return self.isBank ? 80 : 0;
            break;
        case 4:
        case 5:
            return self.selectBankAccount ? 80 : 0;
            break;
            
        default:
            break;
    }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}



@end
